﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.IO;
using System.Linq;
using System.Net.Configuration;
using System.Security;
using System.Threading;
using System.Web;
using AppPressFramework;
using ApplicationClasses;

namespace Application
{

    public class ApplicationSettings : AppPressSettings
    {
        public string LogoPath;
        public string LogoPathSmall;
        public string DocsRootUrl;
        public string CompanyUrl;
        public string MappingFolder;

    }
    public class AppPressApplication
    {
        public static ApplicationSettings Settings = null;

        internal static void InitApplication()
        {
            if (Settings != null)
                throw new Exception("InitApplication Called Already");
            try
            {
                Settings = new ApplicationSettings();
                var smtpSection = (SmtpSection)ConfigurationManager.GetSection("system.net/mailSettings/smtp");
                if (smtpSection.From == null)
                    throw new Exception("Please configure system.net/mailSettings/smtp in web.config. If you are not going to use email then remove this exception.");
                Settings.DebugEmail = "support@sysmates.com"; // Add email you would like to use when Application is working in Debug mode

                Settings.databaseType = DatabaseType.SqlServer;

                Settings.ConnectionStringName = "AppPressSqlServer";

                Settings.MappingFolder = "Default";
                Settings.NetDateFormat = "dd-MMM-yyyy";
                Settings.NetDateTimeFormat = "dd-MMM-yyyy HH:mm";
                if (Settings.databaseType == DatabaseType.SqlServer)
                    Settings.SQLDateFormat = "dd-MMM-yyyy";
                else // MySQL
                    Settings.SQLDateFormat = "%d/%m/%y";
                Settings.JQueryDateFormat = "dd-M-yy";
                Settings.SessionExpiredRedirectForm = "Login";
                Settings.CompanyUrl = "http://apppress.in/";
                Settings.LogoPath = AppPress.GetBaseUrl() + "Customization/" + Settings.MappingFolder + "/Images/Logo.png";
                Settings.LogoPathSmall = AppPress.GetBaseUrl() + "Customization/" + Settings.MappingFolder + "/Images/Logo_Small.png";
                Settings.DocsRootUrl = AppPress.GetBaseUrl() + "Customization/" + Settings.MappingFolder + "/Docs";

                Settings.applicationAssembly = System.Reflection.Assembly.GetExecutingAssembly();
                Settings.applicationNameSpace = "Application";
                Settings.applicationClassName = "AppLogic";

                Settings.pluginAssemblyNames = new List<string> { "Plugin-Reporting.dll" };
#if DEBUG
                var encryptionKey = "Test Key";
#else
            // It is application developer to securily provide the encryptionKey to AppPress
            string encryptionKey = "ReleaseKey";
#endif
                if (encryptionKey != null)
                {
                    Settings.encryptionKey = new SecureString();
                    foreach (var ch in encryptionKey)
                        Settings.encryptionKey.AppendChar(ch);
                }
                string ip = System.Web.HttpContext.Current.Request.UserHostAddress;
                bool IsLocalHost = (ip == "127.0.0.1" || ip == "::1");
                Settings.developer =
#if DEBUG
 true;
#else
                    false;
#endif
                Settings.useDebugEmail = IsLocalHost;

                Settings.Instances.Add(new AppPressInstance { InstanceId = 1, InstanceBaseUrl = AppPress.GetBaseUrl() + "AppPress.aspx", LocalInstance = AppPress.GetBaseUrl() == "http://localhost:61131/" });
                //Settings.Instances.Add(new AppPressInstance { InstanceId = 2, InstanceBaseUrl = "http://localhost:61132/AppPress.aspx", LocalInstance = AppPress.GetBaseUrl() == "http://localhost:61132/" });

                AppPress.InitAppPress(Settings);
#if DEBUG
                // just in case you host Debug version on server
                if (!IsLocalHost)
                    throw new Exception("Debug version is hosted on server. Need release version to run application.");
#endif
            }
            catch
            {
                Settings = null;
                throw;
            }
        }
    }

    public partial class AppLogic
    {
        public static void Init(AppPress a, ErrorFormClass ErrorForm)
        {
            if (a.sessionData.UserData.ContainsKey(AppPressKeys.ErrorFormException))
            {
                var cEx = (CustomizeException)a.sessionData.UserData[AppPressKeys.ErrorFormException];
                string errorMsg1 = cEx.Message;
                if (!errorMsg1.StartsWith("Error"))
                    errorMsg1 = "Error: " + errorMsg1;
                string errorMsg2 = "StackTrace:<br/>" + cEx.StackTrace;
                if (!cEx.InnerExMessage1.IsNullOrEmpty())
                {
                    errorMsg1 += "<br/><br/> InnerException1: " + cEx.InnerExMessage1;
                    errorMsg2 += "<br/><br/> InnerStackTrace1: " + cEx.InnerExStackTrace1;
                }
                if (!cEx.InnerExMessage2.IsNullOrEmpty())
                {
                    errorMsg1 += "<br/><br/> InnerException2: " + cEx.InnerExMessage2;
                    errorMsg2 += "<br/><br/> InnerStackTrace2: " + cEx.InnerExStackTrace2;
                }
                ErrorForm.Message.val = //a.PageURL["Message"] + 
                    "<br/>" + errorMsg1 +
                    "<br/><span style='color:#366092; display:none'>" + errorMsg2.Replace("\r\n", "<br/>") + "</span>";
            }
            else
            {
                ErrorForm.Message.val = a.PageURL["Message"];
            }
        }
    }
}